iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

Daily Coding!一日一刷題系列 第 4

Day03|Codewars 刷題日 (2)

  • 分享至 

  • xImage
  •  

今天是實習的最後一天,
還要面對下禮拜就要開學的事實 q_q
好不想上課RRRRRRR(倒

6kyu. Persistent Bugger.

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example:

 persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.
 persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.
 persistence(4) => 0   # Because 4 is already a one-digit number.

就一個非常普通的各個位數相乘,
乘到最後 < 10 時印出迴圈次數。

def persistence(n):
   count = 0
   while n > 9:
       t = 1
       while n != 0:
           t *= n % 10
           n //= 10
       n = t
       count += 1
   return count

從這題其他大佬的程式中學到了 reduce() 的用法,
可以自行定義一種方式將串列資料累積,
所以可以改為

n = reduce(lambda x, y: x * y, [int(x) for x in str(n)], 1)

看起來簡潔有力 (`・ω・´)


6kyu. Count the smiley faces!

Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]

Example cases:

countSmileys([':)', ';(', ';}', ':-D']);       // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']);     // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;

大致上這題的話,
不會正則表達式的朋友們(例如:我 qwq),
最快就是直接暴力破解法,
2[: or ;] * 3[No, -, ~] * 2[) or D] = 12 種。

def count_smileys(arr):
    count = 0
    for i in arr:
        if i == ':)' or i == ':D' or i == ';)' or i == ';D' or i == ':-)' or i == ':-D' or i == ';-)' or i == ';-D' or i == ':~)' or i == ':~D' or i == ';~)' or i == ';~D':
            count += 1
    return count

看完大佬的解答,
大致上表達式為:

[:;][-~]?[)D] 
[:;][-~]*[)D] 

中括號內放上符合的字元,
[-~]? → [-~] 出現 0 次 或 1 次
[-~]* → [-~] 出現 0 次以上

該來乖乖學 正則表達式了 qwq


上一篇
Day02|Codewars 刷題日 (1)
下一篇
Day04|Codewars 刷題日 (3)
系列文
Daily Coding!一日一刷題7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言